package leetcode_cn;

import java.util.Stack;

/**
 * 逆波兰表达式求值
 *
 * @author briarbear
 * @blog https://briarbear.github.io
 * @date 2018-09-04 14:48
 */
public class EvalRPN {

    public int evalRPN(String[] tokens) {
        /**
         * 用栈来保存操作数
         */
        Stack<Integer> stack = new Stack<>();
        int len = tokens.length;
        int n1,n2;
        for (int i = 0; i < len; i++) {
            switch (tokens[i]){
                case "+":n2 = stack.pop();n1 = stack.pop();stack.push(n1+n2);break;
                case "-":n2 = stack.pop();n1 = stack.pop();stack.push(n1-n2);break;
                case "*":n2 = stack.pop();n1 = stack.pop();stack.push(n1*n2);break;
                case "/":n2 = stack.pop();n1 = stack.pop();stack.push(n1/n2);break;
                default:stack.push(Integer.valueOf(tokens[i]));
            }
        }
        return stack.pop();
    }

    public static void main(String[] args) {
        System.out.println(new EvalRPN().evalRPN(new String[]{"2", "1", "+", "3", "*"}));
        System.out.println(new EvalRPN().evalRPN(new String[]{"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"}));
    }
}
